<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
    <th:block th:include="include :: header('修改作业-课程-班级记录')" />
    <th:block th:include="include :: datetimepicker-css" />
</head>
<body class="white-bg">
    <div class="wrapper wrapper-content animated fadeInRight ibox-content">
        <form class="form-horizontal m" id="form-class-edit" th:object="${jobCourseClass}">
            <input name="id" th:field="*{id}" type="hidden">
            <input name="courseId" th:field="*{courseId}" type="hidden">
            <input name="groupId" th:field="*{groupId}" type="hidden">
            <input name="url" th:field="*{url}" type="hidden">
            <div class="form-group">
                <label class="col-sm-3 control-label">课程名称：</label>
                <div class="col-sm-8">
                    <input name="courseId" th:field="*{className}" class="form-control" type="text">
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label">选择需要布置作业的班级：</label>
                <div class="col-sm-8">
                    <select class="form-control m-b" multiple id="classIds">
                        <option th:each="grade : ${classGradesList}" th:text="${grade.name}"
                                th:value="${grade.id}"></option>
                    </select>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label">章节/知识点描述：</label>
                <div class="col-sm-8">
                    <input name="knowledgeDescription" th:field="*{knowledgeDescription}" class="form-control" type="text">
                </div>
            </div>
            <div class="layui-card" id="evaluateAbilityRelevanceCard">
                <div class="layui-card-header">
                    <fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;font-weight: bold">
                        <legend>作业布置</legend>
                    </fieldset>
                </div>
                <div class="layui-card-body">
                    <table id="evaluateAbilityRelevance" lay-filter="evaluateAbilityRelevance"></table>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label">开始时间：</label>
                <div class="col-sm-8">
                    <div class="input-group date">
                        <input name="beginTime" th:value="${#dates.format(jobCourseClass.beginTime, 'yyyy-MM-dd')}" class="form-control" placeholder="yyyy-MM-dd" type="text">
                        <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                    </div>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label">截至时间：</label>
                <div class="col-sm-8">
                    <div class="input-group date">
                        <input name="endTime" th:value="${#dates.format(jobCourseClass.endTime, 'yyyy-MM-dd')}" class="form-control" placeholder="yyyy-MM-dd" type="text">
                        <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                    </div>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label">补交时间：</label>
                <div class="col-sm-8">
                    <div class="input-group date">
                        <input name="makeUpTime" th:value="${#dates.format(jobCourseClass.makeUpTime, 'yyyy-MM-dd')}" class="form-control" placeholder="yyyy-MM-dd" type="text">
                        <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                    </div>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label">补交扣分：</label>
                <div class="col-sm-8">
                    <input name="deductScore" th:field="*{deductScore}" class="form-control" type="text">
                </div>
            </div>
        </form>
    </div>
    <th:block th:include="include :: footer" />
    <th:block th:include="include :: datetimepicker-js" />

    <script th:inline="javascript">
        var prefix = ctx + "system/job";
        Array.prototype.insert = function(index) {
            index = Math.min(index, this.length);
            arguments.length > 1
            && this.splice.apply(this, [index, 0].concat([].pop.call(arguments)))
            && this.insert.apply(this, arguments);
            return this;
        };

        $("#form-class-edit").validate({
            focusCleanup: true
        });


        (function () {
            if([[${jobCourseClass}]].classIds){
                var classIds = [[${jobCourseClass}]].classIds.split(",")
                console.log('classIds is',classIds)
                $("#classIds").val(classIds)
            }
        })();

        // 课程目标表格组件
        layui.use(['table','layer'], function () {
            var table = layui.table;
            var layer = layui.layer;


            // 试题布置作业表格
            table.render({
                height:'120',
                elem: '#evaluateAbilityRelevance'
                ,id:'evaluateAbilityRelevanceId'
                ,toolbar:true
                ,defaultToolbar:[{
                    title:'新增选择题'
                    ,layEvent:'addRow1'
                    ,icon:'layui-icon-radio'
                },{
                    title:'新增填空题'
                    ,layEvent:'addRow2'
                    ,icon:'layui-icon-addition'
                },{
                    title:'新增简答题'
                    ,layEvent:'addRow3'
                    ,icon:'layui-icon-list'
                },{
                    title:'新增文件上传题'
                    ,layEvent:'addRow4'
                    ,icon:'layui-icon-release'
                }]
                ,height: 312
                ,data:[[${jobCourseClassList}]]
                ,cols: [[ //表头
                    {field: 'id', title: 'ID', hide:true }
                    ,{field: 'type', title: '作业类型'}
                    ,{field: 'title', title: '题目', edit:'text'}
                    ,{field: 'score', title: '分值', edit:'text'}
                    ,{field: 'option', title: '选项', edit:'text'}
                    ,{field: 'optionanswer', title: '选项答案',edit:'text'}
                    ,{field: 'answer', title: '正确答案',edit:'text'}
                    ,{fixed: 'right', align:'center', toolbar: '#evaluateAbilityRelevanceRowToolbar'}
                ]]
                , done : function(res, curr, count) {
                    //如果是异步请求数据方式，res即为你接口返回的信息。
                    //如果是直接赋值的方式，res即为：{data: [], count: 99} data为当前页数据、count为数据总长度
                    console.log(res);

                    //得到当前页码
                    console.log(curr);

                    //得到数据总量
                    console.log(count);

                    // 合并单元格
                    evaluateAbilityRelevanceCardMerge(res);
                }
            });

            table.on('toolbar(evaluateAbilityRelevance)',function (obj) {
                var courseTargetCheckStatus = table.checkStatus(obj.config.id)
                var checkStatus = table.checkStatus(obj.config.id)
                switch (obj.event) {
                    case 'addRow1':
                        buttonArr = [];//清空数组
                        var evaluateAbilityRelevanceData = table.cache.evaluateAbilityRelevanceId;
                        console.log('evaluateAbilityRelevanceData is',evaluateAbilityRelevanceData)
                        for (var i = 0; i < evaluateAbilityRelevanceData.length; i++) {
                            buttonArr.push(evaluateAbilityRelevanceData[i]);      //将之前的数组存储
                        }
                        var currentGroupId
                        if(evaluateAbilityRelevanceData.length > 0){
                            currentGroupId = evaluateAbilityRelevanceData[evaluateAbilityRelevanceData.length-1].id + 1
                        }else {
                            currentGroupId = 1
                        }
                        console.log('currentGroupId is',currentGroupId)
                        //在尾部新增一行空数据，实现增行效果,id设置为最近一条数据+1
                        buttonArr.push({
                            id:getRandom(),
                            type:'选择题',
                            title:'',
                            score:0,
                            option:'',
                            optionanswer:'',
                        });
                        table.reload("evaluateAbilityRelevanceId", {
                            data: buttonArr   // 将新数据重新载入表格
                        })
                        layer.msg('添加成功')
                        break;
                    case 'addRow2':
                        buttonArr = [];//清空数组
                        var evaluateAbilityRelevanceData = table.cache.evaluateAbilityRelevanceId;
                        console.log('evaluateAbilityRelevanceData is',evaluateAbilityRelevanceData)
                        for (var i = 0; i < evaluateAbilityRelevanceData.length; i++) {
                            buttonArr.push(evaluateAbilityRelevanceData[i]);      //将之前的数组存储
                        }
                        var currentGroupId
                        if(evaluateAbilityRelevanceData.length > 0){
                            currentGroupId = evaluateAbilityRelevanceData[evaluateAbilityRelevanceData.length-1].id + 1
                        }else {
                            currentGroupId = 1
                        }
                        console.log('currentGroupId is',currentGroupId)
                        //在尾部新增一行空数据，实现增行效果,id设置为最近一条数据+1
                        buttonArr.push({
                            id:getRandom(),
                            type:'填空题',
                            title:'',
                            score:0,
                            option:'',
                            optionanswer:'',
                        });
                        table.reload("evaluateAbilityRelevanceId", {
                            data: buttonArr   // 将新数据重新载入表格
                        })
                        layer.msg('添加成功')
                        break;
                    case 'addRow3':
                        buttonArr = [];//清空数组
                        var evaluateAbilityRelevanceData = table.cache.evaluateAbilityRelevanceId;
                        console.log('evaluateAbilityRelevanceData is',evaluateAbilityRelevanceData)
                        for (var i = 0; i < evaluateAbilityRelevanceData.length; i++) {
                            buttonArr.push(evaluateAbilityRelevanceData[i]);      //将之前的数组存储
                        }
                        var currentGroupId
                        if(evaluateAbilityRelevanceData.length > 0){
                            currentGroupId = evaluateAbilityRelevanceData[evaluateAbilityRelevanceData.length-1].id + 1
                        }else {
                            currentGroupId = 1
                        }
                        console.log('currentGroupId is',currentGroupId)
                        //在尾部新增一行空数据，实现增行效果,id设置为最近一条数据+1
                        buttonArr.push({
                            id:getRandom(),
                            type:'简答题',
                            title:'',
                            score:0,
                            option:'',
                            optionanswer:'',
                        });
                        table.reload("evaluateAbilityRelevanceId", {
                            data: buttonArr   // 将新数据重新载入表格
                        })
                        layer.msg('添加成功')
                        break;
                    case 'addRow4':
                        buttonArr = [];//清空数组
                        var evaluateAbilityRelevanceData = table.cache.evaluateAbilityRelevanceId;
                        console.log('evaluateAbilityRelevanceData is',evaluateAbilityRelevanceData)
                        for (var i = 0; i < evaluateAbilityRelevanceData.length; i++) {
                            buttonArr.push(evaluateAbilityRelevanceData[i]);      //将之前的数组存储
                        }
                        var currentGroupId
                        if(evaluateAbilityRelevanceData.length > 0){
                            currentGroupId = evaluateAbilityRelevanceData[evaluateAbilityRelevanceData.length-1].id + 1
                        }else {
                            currentGroupId = 1
                        }
                        console.log('currentGroupId is',currentGroupId)
                        //在尾部新增一行空数据，实现增行效果,id设置为最近一条数据+1
                        buttonArr.push({
                            id:getRandom(),
                            type:'文件上传题',
                            title:'',
                            score:0,
                            option:'',
                            optionanswer:'',
                        });
                        table.reload("evaluateAbilityRelevanceId", {
                            data: buttonArr   // 将新数据重新载入表格
                        })
                        layer.msg('添加成功')
                        break;
                }
            })

            table.on('tool(evaluateAbilityRelevance)',function (obj) {
                var data = obj.data; //获得当前行数据
                console.log('data is',data)
                var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
                var tr = obj.tr; //获得当前行 tr 的 DOM 对象（如果有的话）

                if(layEvent === 'setSign'){ //查看
                    //do somehing
                } else if(layEvent === 'del'){ //删除
                    layer.confirm('真的删除行么', function(index){
                        buttonArr = [];//清空数组
                        var evaluateAbilityRelevanceData = table.cache.evaluateAbilityRelevanceId;
                        for (var i = evaluateAbilityRelevanceData.length - 1; i >= 0 ; i--) {
                            if(evaluateAbilityRelevanceData[i].id === data.id){
                                evaluateAbilityRelevanceData.splice(i,1)
                                break
                            }
                        }
                        for (var i = 0; i < evaluateAbilityRelevanceData.length; i++) {
                            buttonArr.push(evaluateAbilityRelevanceData[i]);      //将之前的数组存储
                        }
                        table.reload("evaluateAbilityRelevanceId", {
                            data: buttonArr   // 将新数据重新载入表格
                        })
                        layer.close(index)
                    });
                } else if(layEvent === 'edit'){ //编辑
                    //do something
                    //同步更新缓存对应的值
                    obj.update({
                        data
                    });
                    layer.msg('保存成功')
                } else if(layEvent === 'LAYTABLE_TIPS'){
                    layer.alert('Hi，头部工具栏扩展的右侧图标。');
                } else if(layEvent === 'add'){ // 新增
                    buttonArr = [];//清空数组
                    var evaluateAbilityRelevanceData = table.cache.evaluateAbilityRelevanceId;
                    var index
                    for (var i = evaluateAbilityRelevanceData.length - 1; i >= 0 ; i--) {
                        if(evaluateAbilityRelevanceData[i].id === data.id){
                            index = i
                            break
                        }
                    }
                    for (var i = 0; i < evaluateAbilityRelevanceData.length; i++) {
                        buttonArr.push(evaluateAbilityRelevanceData[i]);      //将之前的数组存储
                    }
                    console.log('evaluateAbilityRelevanceData is',evaluateAbilityRelevanceData)
                    console.log('index is',index)
                    //在该数据后部增加一条数据
                    buttonArr.insert(index+1,{
                        id:data.id,
                        type:data.type,
                        title:'',
                        score:0,
                        answer:''
                    });
                    table.reload("evaluateAbilityRelevanceId", {
                        data: buttonArr   // 将新数据重新载入表格
                    })
                    layer.msg('添加成功')
                }
            })


            table.on('edit(evaluateAbilityRelevance)', function(obj){ //注：edit是固定事件名，test是table原始容器的属性 lay-filter="对应的值"
                console.log(obj.value); //得到修改后的值
                console.log(obj.field); //当前编辑的字段名
                console.log(obj.data); //所在行的所有相关数据
                var data = obj.data
                buttonArr = [];//清空数组
                var evaluateAbilityRelevanceData = table.cache.evaluateAbilityRelevanceId;
                for (var i = evaluateAbilityRelevanceData.length - 1; i >= 0 ; i--) {
                    if(evaluateAbilityRelevanceData[i].id === data.id){
                        evaluateAbilityRelevanceData[i].courseObjectives = data.courseObjectives
                    }
                }
                for (var i = 0; i < evaluateAbilityRelevanceData.length; i++) {
                    buttonArr.push(evaluateAbilityRelevanceData[i]);      //将之前的数组存储
                }
                table.reload("evaluateAbilityRelevanceId", {
                    data: buttonArr   // 将新数据重新载入表格
                })
            });
        });

        function getRandom(){
            var num = '';
            for (var i = 0; i < 11; i++) {
                num += Math.floor(Math.random() * 10);
            }
            console.log(num);
            return num;
        }

        function evaluateAbilityRelevanceCardMerge(res){
            var data = res.data;
            console.log('merge res.data is', data)
            var mergeIndex = 0;//定位需要添加合并属性的行数
            var mark = 1; //这里涉及到简单的运算，mark是计算每次需要合并的格子数
            var columsName = ['id','type','title','score','answer'];//需要合并的列名称
            var columsIndex = [0,1,2,3,6];//需要合并的列索引值

            for (var k = 0; k < columsName.length; k++) { //这里循环所有要合并的列
                var trArr = $("#evaluateAbilityRelevanceCard").find("tbody tr");//获取evaluateAbilityRelevanceCard下表格所有的tbody tr
                console.log('trArr is',trArr)
                for (var i = 1; i < res.data.length; i++) { //这里循环表格当前的数据
                    var tdCurArr = trArr.eq(i).find("td").eq(columsIndex[k]);//获取当前行的当前列
                    var tdPreArr = trArr.eq(mergeIndex).find("td").eq(columsIndex[k]);//获取相同列的第一列

                    if (data[i][columsName[0]] === data[i-1][columsName[0]]) { //后一行的值与前一行的值做比较，相同就需要合并
                        mark += 1;
                        tdPreArr.each(function () {//相同列的第一列增加rowspan属性
                            $(this).attr("rowspan", mark);
                        });
                        tdCurArr.each(function () {//当前行隐藏
                            $(this).css("display", "none");
                        });
                    }else {
                        mergeIndex = i;
                        mark = 1;//一旦前后两行的值不一样了，那么需要合并的格子数mark就需要重新计算
                    }
                }
                mergeIndex = 0;
                mark = 1;
            }
        }


        function submitHandler() {
            var saveData = {}
            var evaluateAbilityRelevanceData = layui.table.cache.evaluateAbilityRelevanceId;
            console.log('evaluateAbilityRelevanceData is', evaluateAbilityRelevanceData)
            saveData.jobList = evaluateAbilityRelevanceData
            var formData = $('#form-class-edit').serializeArray()
            console.log('formData is', formData)
            formData.map(item =>{
                saveData[item.name] = item.value
            })
            var classIds = $('#classIds').val()
            console.log('classIds is',classIds)
            if(classIds){
                saveData.classIds = classIds.join(',')
            }
            console.log('saveData is', saveData)

            if ($.validate.form()) {
                $.operate.saveJson(prefix + "/edit", JSON.stringify(saveData));
            }
        }

        $("input[name='beginTime']").datetimepicker({
            format: "yyyy-mm-dd",
            minView: "month",
            autoclose: true
        });

        $("input[name='endTime']").datetimepicker({
            format: "yyyy-mm-dd",
            minView: "month",
            autoclose: true
        });

        $("input[name='makeUpTime']").datetimepicker({
            format: "yyyy-mm-dd",
            minView: "month",
            autoclose: true
        });
    </script>
</body>
</html>
